<template>
  <div>
    <PageWrapper contentBackground contentClass="flex" dense contentFullHeight fixedHeight>
      <ImagePreview :imageList="imgList" />
      <BasicTable @register="registerTable">
        <template #id="{ record }">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:picture',
                tooltip: '预览',
                onClick: handlePreview.bind(null, record),
              },
            ]"
          />
        </template>

        <template #renderHouse="{ record, column }">
          <Popover
            :content="h(HousePopover, { pcztVal: record, underMode: underModeRef })"
            :title="'详情 - ' + record['fwbh']"
            placement="right"
          >
            <Card :bordered="false" hoverable size="small">
              <Descriptions :title="record['fwbh']" :column="1" size="small">
                <DescriptionItem label="编号"> {{ record['yhfwbh'] }} </DescriptionItem>
                <DescriptionItem label="地址"> {{ record['address'] }} </DescriptionItem>
              </Descriptions>
            </Card>
          </Popover>
        </template>

        <template #toolbarLeft> </template>

        <!-- <template #toolbar>
          <a-button type="primary" @click="handleReloadCurrent">
            <reload-outlined />
          </a-button>
          <a-button type="primary" @click="handleReload"> <double-left-outlined /> </a-button>
        </template> -->

        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                icon: 'clarity:note-edit-line',
                tooltip: '审核',
                onClick: handleAudit.bind(null, record),
              },
            ]"
          />
        </template>
      </BasicTable>
    </PageWrapper>
    <AuditModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, computed, unref, toRefs, reactive, h } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { getBasicColumns, getSearchFormSchema } from './tableData';
  import { PageWrapper } from '/@/components/Page';
  import { createImgPreview, ImagePreview } from '/@/components/Preview/index';
  import { houseListApi } from '/@/api/demo/table';
  import { useModal } from '/@/components/Modal';
  import AuditModal from './AuditModal.vue';
  import { ReloadOutlined, DoubleLeftOutlined } from '@ant-design/icons-vue';
  import { useRouter, useRoute } from 'vue-router';
  import { Tabs, Space, Divider, Tag, Checkbox, Card, Descriptions, Popover } from 'ant-design-vue';
  import { useGlobSetting } from '/@/hooks/setting';
  const globSetting = useGlobSetting();
  const imgList: string[] = [];

  import { HousePopover } from '/@/components/HousePopover/index';

  export default defineComponent({
    name: 'FetchHouseTable',
    components: {
      BasicTable,
      PageWrapper,
      TableAction,
      AuditModal,
      ImagePreview,
      ReloadOutlined,
      DoubleLeftOutlined,
      Tabs,
      HousePopover,
      Space,
      Divider,
      Tag,
      Checkbox,
      Popover,
      CardMeta: Card.Meta,
      Card,
      Descriptions,
      DescriptionItem: Descriptions.Item,
    },
    props: {
      underMode: {
        type: Array,
        default: () => [],
      },
    },
    emits: ['onHouseSelected'],
    setup(props, { emit }) {
      const viewList = ref(true);
      const checkFirst = ref(true);
      const checkFirstKey = reactive([]);
      const selectedHouseIds: string[] = reactive([]);
      const router = useRouter();
      const route = useRoute();

      const underModeRef = ref(props.underMode);

      const [registerModal, { openModal }] = useModal();
      const [registerTable, { reload }] = useTable({
        //title: '房屋列表',
        api: houseListApi,
        columns: getBasicColumns(),
        rowKey: 'id',
        formConfig: {
          schemas: getSearchFormSchema(underModeRef.value),
        },
        useSearchForm: true,
        pagination: { pageSize: 10 },
        afterFetch: (resultItems) => {
          selectedHouseIds.length = 0;
          if (resultItems.length > 0) {
            selectedHouseIds.push(resultItems[0].id);
          }
          return Promise.resolve(resultItems);
        },
        rowSelection: {
          onChange: (selectedRowKeys: string[], _: []) => {
            if (selectedHouseIds.length > 0) {
              selectedHouseIds[0] = selectedRowKeys[0];
            } else {
              selectedHouseIds.push(selectedRowKeys[0]);
            }
            emit('onHouseSelected', selectedRowKeys[0]);
          },
          type: 'radio',
          selectedRowKeys: selectedHouseIds,
        },

        // actionColumn: {
        //   width: 120,
        //   title: '操作',
        //   dataIndex: 'action',
        //   slots: { customRender: 'action' },
        // },
      });

      function handleReloadCurrent() {
        reload();
      }

      function handleSwitchMode() {
        viewList.value = !viewList.value;
      }

      function handleAudit(record: Recordable) {
        openModal(true, {
          record,
          isUpdate: true,
        });
      }

      function handlePreview(record: Recordable) {
        const onImgLoad = ({ index, url, dom }) => {
          console.log(`第${index + 1}张图片已加载，URL为：${url}`, dom);
        };
        imgList.length = 0;
        if (record.phid) {
          let photos = record.phid.split(',');
          photos.forEach((ele) => {
            if (ele) imgList.push(`${globSetting.apiBaseUrl}/api/v1/images/${ele}`);
          });
        }
        // 可以使用createImgPreview返回的 PreviewActions 来控制预览逻辑，实现类似幻灯片、自动旋转之类的骚操作
        createImgPreview({ imageList: imgList, defaultWidth: 700, rememberState: true, onImgLoad });
      }

      function handleReload() {
        reload({
          page: 1,
        });
      }
      function handleSuccess() {
        reload();
      }
      return {
        imgList,
        h,
        underModeRef,
        registerModal,
        registerTable,
        handleAudit,
        handlePreview,
        handleReloadCurrent,
        handleSwitchMode,
        handleReload,
        handleSuccess,
        HousePopover,
      };
    },
  });
</script>
